import { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate, Link } from 'react-router-dom';
import { loginTeacher } from '@/services/teacher';
import { login } from '@/redux/slices/authSlice';
import { fetchCSRFToken } from '@/utils/csrf';
import '@/styles/pages/auth.scss';

const Login = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  
  const [teacherId, setTeacherId] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [loginSuccess, setLoginSuccess] = useState(false);
  
  // 页面加载时获取CSRF令牌
  useEffect(() => {
    fetchCSRFToken();
  }, []);
  
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    
    if (!teacherId.trim()) {
      setError('请输入教师号');
      return;
    }
    
    if (!password) {
      setError('请输入密码');
      return;
    }
    
    try {
      setLoading(true);
      const res = await loginTeacher(teacherId, password);
      
      console.log('登录响应完整数据:', res);
      
      // 检查登录是否成功 (后端返回code为2000表示成功)
      if (res.code === 2000 && res.data) {
        console.log('登录成功，获取到的数据:', res.data);
        
        // 检查是否有token和teacher数据
        if (res.data.token) {
          // 手动存储token到localStorage
          localStorage.setItem('token', res.data.token);
          console.log('手动设置token后:', localStorage.getItem('token'));
          
          // 存储teacher信息
          if (res.data.teacher) {
            localStorage.setItem('teacher', JSON.stringify(res.data.teacher));
          }
          
          // 更新Redux状态
          dispatch(login({
            token: res.data.token,
            teacher: res.data.teacher
          }));
          
          // 显示登录成功提示
          setLoginSuccess(true);
          
          // 使用延时确保localStorage存储完成
          setTimeout(() => {
            // 直接使用window.location.href进行页面跳转
            window.location.href = '/';
          }, 1000);
        } else {
          setError('登录成功但未获取到token');
        }
      } else {
        setError(res.message || '登录失败');
      }
    } catch (err: any) {
      console.error('登录出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div className="auth-container">
      <div className="auth-form-box">
        <h2 className="title">智慧课堂教师端登录</h2>
        
        {loginSuccess && <div className="success-message">登录成功，正在跳转...</div>}
        {error && <div className="error-message">{error}</div>}
        
        <form className="auth-form" onSubmit={handleSubmit}>
          <div className="form-item">
            <label htmlFor="teacherId">教师号</label>
            <input
              type="text"
              id="teacherId"
              value={teacherId}
              onChange={(e) => setTeacherId(e.target.value)}
              placeholder="请输入教师号"
            />
          </div>
          
          <div className="form-item">
            <label htmlFor="password">密码</label>
            <input
              type="password"
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="请输入密码"
              autoComplete="current-password"
            />
          </div>
          
          <button 
            className="btn btn-primary submit-btn" 
            type="submit"
            disabled={loading || loginSuccess}
          >
            {loading ? '登录中...' : '登录'}
          </button>
        </form>
        
        <div className="auth-footer">
          <span>还没有账号？</span>
          <Link to="/register">立即注册</Link>
        </div>
      </div>
    </div>
  );
};

export default Login; 